package com.ljkj.cordial.chat.presenter;

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.adapter.ChatAdapter;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.ChatTableUnit;
import com.ljkj.cordial.chat.bean.PayLoad;
import com.ljkj.cordial.chat.dao.AlbumTableBean;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.ljkj.cordial.chat.util.SpeechVoiceUtil;
import com.nic.view.util.AndroidFileUtil;
import com.nic.view.util.JToast;
import com.nic.view.widget.CircleImageView;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 视频
 */
public class VideoPresenter extends AChatPresenter {
    public VideoPresenter(int direction) {
        super(direction);
//        LayoutInflater.from(view.getContext()).inflate(R.layout.item_chat_right_video, null);
    }

    @Override
    public RecyclerView.ViewHolder getViewHolder(View view) {
        if (getDirection() == LEFT) {
            return new ViewLeftHolder(view);
        }
        return new ViewRightHolder(view);
    }

    @Override
    public void bindViewHolder(RecyclerView.ViewHolder holder, Object obj, int position) {
        ChatTableUnit item = (ChatTableUnit) obj;
        Context context = holder.itemView.getContext();
        if (getDirection() == LEFT) {
            ViewLeftHolder viewLeftHolder = (ViewLeftHolder) holder;
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewLeftHolder.llVideoMsg.getLayoutParams();
            if (getChatType() == Canstants.SINGLE_CHAT) {
                viewLeftHolder.tvTitle.setVisibility(View.GONE);
                params.topMargin = context.getResources().getDimensionPixelOffset(R.dimen.dimen_8);
                viewLeftHolder.llVideoMsg.setLayoutParams(params);
            } else {
                viewLeftHolder.tvTitle.setVisibility(View.VISIBLE);
                viewLeftHolder.tvTitle.setText(TextUtils.isEmpty(item.getAlias()) ? item.getTargetName() : item.getAlias());
            }
            setVisible(viewLeftHolder.cb, item.isVisible());
            setCheck(viewLeftHolder.cb, item.isChecked());
            viewLeftHolder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    item.setChecked(isChecked);
                    if (getOnCListener() != null) {
                        getOnCListener().onItemCheckChange(buttonView, item, position, isChecked);
                    }
                }
            });
            if (item.getSendState() == ChatTableUnit.SEND_ING) {
                viewLeftHolder.chatItemProgress.show();
            } else if (item.getSendState() == ChatTableUnit.SEND_SUCCESS) {
                viewLeftHolder.chatItemProgress.hide();
            } else if (item.getSendState() == ChatTableUnit.SEND_FAIL) {
                viewLeftHolder.chatItemProgress.hide();
            }
            viewLeftHolder.ivVideoPlay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showVideo(viewLeftHolder.chatItemProgress, viewLeftHolder.ivVideoPlay, item);
                }
            });
            viewLeftHolder.ivVideoFrame.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (getOnCListener() != null) {
                        getOnCListener().onItemLongClick(v, item, position);
                        return true;
                    }
                    return false;
                }
            });
            viewLeftHolder.ivIsVisitor.setVisibility(IMSContacts.UserType.TOURISTS_USER.equals(item.getTargetType()) ? View.VISIBLE : View.GONE);
            if (isLoadAccess()) {
                showThumbPicture(item, viewLeftHolder.ivVideoFrame, position);
            } else {
                showThumbPictureDef(item, viewLeftHolder.ivVideoFrame);
            }
            loadAvatar(item, viewLeftHolder.ivAvatar);
            setReadFinishState(viewLeftHolder.tvDownTime, item.isStartReadFinish());
        } else {
            ViewRightHolder viewRightHolder = (ViewRightHolder) holder;
            setVisible(viewRightHolder.cb, item.isVisible());
            setCheck(viewRightHolder.cb, item.isChecked());
            if (item.isVisible()) {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewRightHolder.ivAvatar.getLayoutParams();
                params.addRule(RelativeLayout.LEFT_OF, viewRightHolder.cb.getId());
                params.rightMargin = viewRightHolder.cb.getContext().getResources().getDimensionPixelOffset(R.dimen.dimen_48);
            } else {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewRightHolder.ivAvatar.getLayoutParams();
                params.rightMargin = viewRightHolder.cb.getContext().getResources().getDimensionPixelOffset(R.dimen.dimen_16);
            }
            viewRightHolder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    item.setChecked(isChecked);
                    if (getOnCListener() != null) {
                        getOnCListener().onItemCheckChange(buttonView, item, position, isChecked);
                    }
                }
            });
            viewRightHolder.ivFail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (getOnCListener() != null) {
                        getOnCListener().onItemReloadClick(v, item, position);
                    }
                }
            });
            viewRightHolder.ivVideoPlay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showVideo(viewRightHolder.chatItemProgress, viewRightHolder.ivVideoPlay, item);
                }
            });
            viewRightHolder.ivVideoFrame.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (getOnCListener() != null) {
                        getOnCListener().onItemLongClick(v, item, position);
                        return true;
                    }
                    return false;
                }
            });
            if (isLoadAccess()) {
                showThumbPicture(item, viewRightHolder.ivVideoFrame, position);
            } else {
                showThumbPictureDef(item, viewRightHolder.ivVideoFrame);
            }
            loadAvatar(item, viewRightHolder.ivAvatar);
            setReadFinishState(viewRightHolder.tvDownTime, item.isStartReadFinish());
            refreshSendState(item, viewRightHolder);
        }
    }

    private void refreshSendState(ChatTableUnit item, ViewRightHolder viewRightHolder) {
        if (item.getSendState() == ChatTableUnit.SEND_SUCCESS) {
            viewRightHolder.ivFail.setVisibility(View.GONE);
            viewRightHolder.ivVideoPlay.setVisibility(View.VISIBLE);
            viewRightHolder.chatItemProgress.hide();
        } else if (item.getSendState() == ChatTableUnit.SEND_FAIL) {
            viewRightHolder.chatItemProgress.hide();
            viewRightHolder.ivVideoPlay.setVisibility(View.VISIBLE);
            viewRightHolder.ivFail.setVisibility(View.VISIBLE);
        } else {
            viewRightHolder.ivFail.setVisibility(View.GONE);
            viewRightHolder.ivVideoPlay.setVisibility(View.GONE);
            viewRightHolder.chatItemProgress.show();
        }
    }


    private void showVideo(ContentLoadingProgressBar viewVideoHolder, ImageView ivVideoPlay, ChatTableUnit item) {
        AlbumManageUtil.getInstance().stopVoice();
        if (!TextUtils.isEmpty(item.getAlbumId()) && Long.parseLong(item.getAlbumId()) > 0) {
            ivVideoPlay.setVisibility(View.VISIBLE);
            AlbumTableBean al = AlbumTableBean.queryById(Long.parseLong(item.getAlbumId()));

            if (al != null && !TextUtils.isEmpty(al.getMPath())) {
                File file = new File(al.getMPath());
                if (!file.exists()) {
                    JToast.show(viewVideoHolder.getContext(), "原文件已不存！", Toast.LENGTH_SHORT);
                    return;
                }
                Intent intent = AndroidFileUtil.openFile(al.getMPath());
                if (intent != null) {
                    viewVideoHolder.getContext().startActivity(intent);
                    SpeechVoiceUtil.setAudioMute(viewVideoHolder.getContext(), false);
                }
//                VideoPlayActivity.jumpTo(viewVideoHolder.getContext(),al.getMPath(),item.getThumbPath());
//                new VideoPreviewDialog(viewVideoHolder.getContext()).show(al.getMPath(),al.getMThumbPath());
            } else {
                JToast.show(viewVideoHolder.getContext(), "原文件已不存！", Toast.LENGTH_SHORT);
            }

        } else {
            if (TextUtils.isEmpty(item.getFileUrl())) {
                return;
            }
            if (viewVideoHolder.isShown()) {
                return;
            }
            viewVideoHolder.show();

            ivVideoPlay.setVisibility(View.GONE);
            if (Canstants.SINGLE_CHAT == item.getFromType())
                AlbumManageUtil.getInstance().downLoadFileFriend(item.getFileUrl(), AlbumTableBean.TYPE_VIDEO, item.getTargetId(), new AlbumManageUtil.OnFileResponse() {
                    @Override
                    public void onResult(String path, String fileId) {
                        resultFile(fileId, viewVideoHolder, ivVideoPlay, item);
                    }
                });
            else
                AlbumManageUtil.getInstance().downLoadFileGroupMember(item.getFileUrl(), AlbumTableBean.TYPE_VIDEO
                        , item.getGroupType(), item.getGroupId(), item.getTargetType(), item.getTargetId(), new AlbumManageUtil.OnFileResponse() {
                            @Override
                            public void onResult(String url, String fileId) {
                                resultFile(fileId, viewVideoHolder, ivVideoPlay, item);
                            }
                        });
        }

    }

    private void resultFile(String fileId, ContentLoadingProgressBar viewVideoHolder, ImageView ivVideoPlay, ChatTableUnit item) {
        viewVideoHolder.hide();
        ivVideoPlay.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(fileId) && Long.parseLong(fileId) > 0) {
            item.setAlbumId(fileId);
            ChatTableBean.update(ChatTableUnit.getTable(item));
            AlbumTableBean al = AlbumTableBean.queryById(Long.parseLong(fileId));
            if (!TextUtils.isEmpty(al.getMPath())) {
                Intent intent = AndroidFileUtil.openFile(al.getMPath());
                if (intent != null) {
                    viewVideoHolder.getContext().startActivity(intent);
                    SpeechVoiceUtil.setAudioMute(viewVideoHolder.getContext(), false);
                }
//                VideoPlayActivity.jumpTo(viewVideoHolder.getContext(),al.getMPath(),item.getThumbPath());
//                new VideoPreviewDialog(viewVideoHolder.getContext()).show(al.getMPath(),al.getMThumbPath());
            }
        }
    }

    @Override
    public void bindViewHolder(ChatAdapter chatAdapter, int position, RecyclerView.ViewHolder holder, Object obj, PayLoad payLoad) {
        super.bindViewHolder(chatAdapter, position, holder, obj, payLoad);
        ChatTableUnit item = (ChatTableUnit) obj;
        if (getDirection() == LEFT) {
            ViewLeftHolder viewLeftHolder = (ViewLeftHolder) holder;
            for (int type : payLoad.getType()) {
                if (PayLoad.AVATAR == type)
                    loadAvatar(item, viewLeftHolder.ivAvatar);
                if (PayLoad.FILE == type) {
                    if (isLoadAccess()) {
                        showThumbPicture(item, viewLeftHolder.ivVideoFrame, position);
                    } else {
                        showThumbPictureDef(item, viewLeftHolder.ivVideoFrame);
                    }

                }

                if (PayLoad.DOWN_TIME == type) {
                    if (item.isStartReadFinish()) {
                        viewLeftHolder.tvDownTime.setText(item.getReadFinishFormatTime());
                    }
                }

            }

        } else {
            ViewRightHolder viewRightHolder = (ViewRightHolder) holder;
            for (int type : payLoad.getType()) {
                if (PayLoad.AVATAR == type)
                    loadAvatar(item, viewRightHolder.ivAvatar);
                if (PayLoad.FILE == type) {
                    if (isLoadAccess()) {
                        showThumbPicture(item, viewRightHolder.ivVideoFrame, position);
                    } else {
                        showThumbPictureDef(item, viewRightHolder.ivVideoFrame);
                    }

                }
                if (item.getSendState() == ChatTableUnit.SEND_SUCCESS && PayLoad.DOWN_TIME == type) {
                    if (item.isStartReadFinish() && item.getSendState() == ChatTableUnit.SEND_SUCCESS) {
                        viewRightHolder.tvDownTime.setText(item.getReadFinishFormatTime());
                    }
                }
                if (PayLoad.REQ_STATE == type) {
                    refreshSendState(item, viewRightHolder);
                }
            }
        }
    }

    public static class ViewLeftHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.cb)
        CheckBox cb;
        @BindView(R.id.iv_avatar)
        CircleImageView ivAvatar;
        @BindView(R.id.iv_is_visitor)
        ImageView ivIsVisitor;
        @BindView(R.id.ll_avatar)
        FrameLayout llAvatar;
        @BindView(R.id.tv_title)
        TextView tvTitle;
        @BindView(R.id.iv_video_frame)
        ImageView ivVideoFrame;
        @BindView(R.id.iv_video_play)
        ImageView ivVideoPlay;
        @BindView(R.id.chat_item_progress)
        ContentLoadingProgressBar chatItemProgress;
        @BindView(R.id.ll_video_msg)
        CardView llVideoMsg;
        @BindView(R.id.tv_downTime)
        TextView tvDownTime;

        ViewLeftHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            AChatPresenter.setProgressColor(chatItemProgress);
//            setIsRecyclable(false);
        }
    }

    public static class ViewRightHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.cb)
        CheckBox cb;
        @BindView(R.id.iv_avatar)
        CircleImageView ivAvatar;
        @BindView(R.id.iv_video_frame)
        ImageView ivVideoFrame;
        @BindView(R.id.iv_video_play)
        ImageView ivVideoPlay;
        @BindView(R.id.chat_item_progress)
        ContentLoadingProgressBar chatItemProgress;
        @BindView(R.id.ll_video_msg)
        CardView llVideoMsg;
        @BindView(R.id.iv_fail)
        ImageView ivFail;
        @BindView(R.id.tv_downTime)
        TextView tvDownTime;

        ViewRightHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            AChatPresenter.setProgressColor(chatItemProgress);
//            setIsRecyclable(false);
        }
    }


}
